package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 用于进行身份拦截
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    public StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录拦截器-preHandle");
//从请求头中获取token
        String token = request.getHeader("authorization");
//        如果请求头中没有合法的token
        if (StrUtil.isBlank(token)) {
            response.setStatus(401);
            returnJson(response, Result.fail("token为空"));
            return false;
        }
//        log.info("请求头中的token:{}",
//                token);
        //获取用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
//        获取的用户为空
        if (userMap.isEmpty()) {
            response.setStatus(401);
            returnJson(response, Result.fail("token无效或过期"));
            return false;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
//        log.info("登录存入线程中的用户信息,{}",userDTO);
//        保存用户信息到 ThreadLocal
        UserHolder.saveUser(userDTO);
//        最后放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("拦截器-afterCompletion");
        //        渲染完毕之后，为了避免内存泄露，在使用完 ThreadLocal 后，应该及时调用 remove() 方法移除对应的条目
        UserHolder.removeUser();
    }
    
    /**
     * 将Result对象转换为JSON格式并写入响应体
     * @param response HTTP响应对象
     * @param result 需要返回的Result对象
     */
    private void returnJson(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(result));
        } catch (IOException e) {
            log.error("返回JSON数据失败", e);
        }
    }
}
